package cn.jiadakeji.parent.service.impl;

import cn.jiadakeji.parent.domain.*;
import cn.jiadakeji.parent.dto.ClassCoursePrePlanDTO;
import cn.jiadakeji.parent.dto.ClassCoursePrePlanDetailsDTO;
import cn.jiadakeji.parent.mapper.ClassCoursePrePlanMapper;
import cn.jiadakeji.parent.mapper.CustomerMapper;
import cn.jiadakeji.parent.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author heyanfeng
 * @create 2022-03-14 15:44
 */
@Service
public class ClassCoursePrePlanServiceImpl extends ServiceImpl<ClassCoursePrePlanMapper, ClassCoursePrePlan> implements ClassCoursePrePlanService {

    @Autowired
    private ClassCourseStuPlanService stuPlanService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private CustomerTeacherService teacherService;

    @Autowired
    private SchoolRoomService roomService;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private CourseService courseService;

    @Autowired
    private ThreePartService threePartService;

    @Autowired
    private ThreadPoolExecutor executor;


    /**
     * 获取学生预开课信息
     */
    @Override
    public List<ClassCoursePrePlanDTO> coursePreList(String studentId) {
        // 获取学生预开课信息
        List<String> coursePreIds = stuPlanService.list(new QueryWrapper<ClassCourseStuPlan>()
                .eq("student_id", studentId)).stream().map(item -> {
            return item.getClassCoursePlanId();
        }).collect(Collectors.toList());
        // 查找coursePre信息
        List<ClassCoursePrePlan> planList = baseMapper.selectBatchIds(coursePreIds);
        // 类型转换
        return planList.stream().map(course -> {
            ClassCoursePrePlanDTO classCoursePrePlanDTO = new ClassCoursePrePlanDTO();
            BeanUtils.copyProperties(course, classCoursePrePlanDTO);
            // 设置排班状态
            String status = stuPlanService.getScheduleStatus(course.getId(), studentId);
            classCoursePrePlanDTO.setScheduleStatus(status);
            return classCoursePrePlanDTO;
        }).collect(Collectors.toList());
    }

    /**
     * 预开课详细信息
     */
    @Override
    public ClassCoursePrePlanDetailsDTO coursePreDetail(String coursePreId, String studentId) throws Exception {
        ClassCoursePrePlanDetailsDTO prePlanDetailsDTO = new ClassCoursePrePlanDetailsDTO();
        // 使用异步处理
        /*      1）先要查找prePlan信息,其他查询依赖当前结果
                2）学校，课程，老师，教室信息的查询可以同步进行
                3）第三方机构和预开课信息查询依赖于课程的结果
        */
        //long start = System.currentTimeMillis();
        // 1，根据预开课coursePreId获取预开课信息
        CompletableFuture<ClassCoursePrePlan> prePlanFuture = CompletableFuture.supplyAsync(() -> {
            return baseMapper.selectById(coursePreId);
        }, executor);

        // 2，获取学校信息
        CompletableFuture<Void> schoolFuture = prePlanFuture.thenAcceptAsync(pre -> {
            School school = schoolService.getById(pre.getSchoolId());
            prePlanDetailsDTO.setSchoolName(school.getName());
        }, executor);

        // 3，获取课程信息
        CompletableFuture<Course> courseFuture = prePlanFuture.thenApplyAsync(pre -> {
            Course course = courseService.getById(pre.getCourseId());
            // 3,1转换字段
            String type = "";
            if ("STU".equals(course.getCourseType())) {
                type = "学科";
            } else if ("ART".equals(course.getCourseType())) {
                type = "艺术";
            } else {
                type = "体育";
            }
            prePlanDetailsDTO.setCourseType(type);
            prePlanDetailsDTO.setPrice(course.getPrice());
            prePlanDetailsDTO.setIntroduction(course.getIntroduction());
            return course;
        }, executor);

        // 4，获取老师信息
        CompletableFuture<Void> teacherFuture = prePlanFuture.thenAcceptAsync(pre -> {
            CustomerTeacher teacher = teacherService.getById(pre.getTeacherId());
            String teacherName = customerMapper.getTeacherName(teacher.getCustomerId());
            prePlanDetailsDTO.setTeacherName(teacherName);
        }, executor);

        // 5，获取教室信息
        CompletableFuture<Void> roomFuture = prePlanFuture.thenAcceptAsync(pre -> {
            SchoolRoom room = roomService.getById(pre.getSchoolRoomId());
            prePlanDetailsDTO.setSchoolRoomName(room.getRoomName());
        }, executor);

        // 6，获取第三方机构信息
        CompletableFuture<Void> threePartFuture = courseFuture.thenAcceptAsync(course -> {
            ThreePart threePart = threePartService.getById(course.getThreePartId());
            prePlanDetailsDTO.setThreePartName(threePart.getName());
        }, executor);

        // 7，设置预开课信息
        CompletableFuture<Void> prePlanDtoFuture = courseFuture.thenAcceptAsync(course -> {
            // 7.1查询预开课信息
            ClassCoursePrePlan prePlan = baseMapper.selectOne(new QueryWrapper<ClassCoursePrePlan>().eq("course_id", course.getId()));
            ClassCoursePrePlanDTO classCoursePrePlanDTO = new ClassCoursePrePlanDTO();
            BeanUtils.copyProperties(prePlan, classCoursePrePlanDTO);
            // 7,2设置排班状态
            String status = stuPlanService.getScheduleStatus(prePlan.getId(), studentId);
            classCoursePrePlanDTO.setScheduleStatus(status);
            prePlanDetailsDTO.setClassCoursePrePlanDTO(classCoursePrePlanDTO);
        }, executor);
        CompletableFuture.allOf(schoolFuture, teacherFuture, roomFuture, threePartFuture, prePlanDtoFuture).get();
        //long end = System.currentTimeMillis();
        //System.out.println("时间：" + (end - start));
        return prePlanDetailsDTO;
    }
}
